from transformers import AutoTokenizer, AutoModel
from typing import List, Optional,Dict
from fastapi import FastAPI
from pydantic import BaseModel
import uvicorn
import argparse
from fastapi import Body, FastAPI, File, Form, Query, UploadFile, WebSocket
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from typing import Union
from io import BytesIO
import json
import pydantic
from collections import Counter  
import os
from configs.config import *
from similarOrder import similarOrder_LSH_json,similarOrder_LSH_Excel_api,similarOrder_LSH_Excel_sql
import jieba
if os.path.exists(os.path.join(PROJECT_DIR, "jieba_dict.txt")):
    jieba.load_userdict(os.path.join(PROJECT_DIR, "jieba_dict.txt"))

import logging
if not os.path.exists(os.path.join(PROJECT_DIR, "logs")):
    os.makedirs(os.path.join(PROJECT_DIR, "logs"))
    
logging.basicConfig(filename= os.path.join(PROJECT_DIR, "logs/api.log"), level=logging.INFO, 
                    format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class Sim_Input(BaseModel):
    id: str = Body(..., description="工单编号", example="20231212027285")
    addr: str = Body(..., description="地址", example="拼多多")
    class4:str = Body(..., description="内容分类4", example="网上购物")
    content: str = Body(..., description="工单内容", example="消费维权")
    
class SimeventRequest(BaseModel):
    gd_list: List[Sim_Input] 


class Simevent_Id_Request(BaseModel):
    id_list:list = pydantic.Field(..., description="ids")


class Sim_Output(BaseModel):
    event: str = Body(..., description="工单编号", example="20231212027285")
    num: str = Body(..., description="地址", example="闵行区剑川路201弄144号202室")
    gd_ids: list = pydantic.Field(..., description="Searched ids")
    keywords: list = pydantic.Field(..., description="Keywords")
    # keywords: Dict
class SimeventResponse(BaseModel):
    code: int = pydantic.Field(200, description="HTTP status code")
    msg: str = pydantic.Field("success", description="HTTP status message") 
    results:Sim_Output

class SimeventResponse_error(BaseModel):
    code: int = pydantic.Field(200, description="HTTP status code")
    msg: str = pydantic.Field("success", description="HTTP status message")   

async def Sim_event(request: SimeventRequest):
    gd_list = request.gd_list
    try:
        event,num,gd_ids,keywords = similarOrder_LSH_json(gd_list,is_single = Is_single)
        results = Sim_Output(
            event = event,
            num = num,
            gd_ids= gd_ids,
            keywords = keywords
        )
        
        logger.info(f"<<< code=200, msg=success, event={event}, num={num},gd_ids={gd_ids},keywords={keywords}\n")
        return SimeventResponse(code=200, msg="success", results=results)
        
    except Exception as e:
        logger.error(f"<<< code=500, msg=fail: {e}\n")
        return SimeventResponse(code=500, msg=f"fail: {e}")


async def Sim_event_excel(excel_file: UploadFile):
    try:
        content = await excel_file.read()
        content_io = BytesIO(content)
        # texts, metadata = read_excel_file(content_io, excel_file.filename)
        
        # event,num,gd_ids,keywords = similarOrder_LSH_Excel_api(content_io,is_single = Is_single)
        output_Excel_path = similarOrder_LSH_Excel_api(content_io,is_single = Is_single)
    
        # output = Sim_Output(
        #     event = event,
        #     num = num,
        #     gd_ids= gd_ids,
        #     keywords = keywords
        # )

        # logger.info(f"<<< code=200, msg=success, event={event}, num={num},gd_ids={gd_ids},keywords={keywords}\n")
        return FileResponse(output_Excel_path, filename="processed_excel.xlsx")
        # return SimeventResponse(code=200, msg="success", results=output)
        
    except Exception as e:
        logger.error(f"<<< code=500, msg=fail: {e}\n")
        return SimeventResponse_error(code=500, msg=f"fail: {e}")

async def Sim_event_sql(request: Simevent_Id_Request):
    try:
        id_list = request.id_list
        
        
        
        event,num,gd_ids,keywords = similarOrder_LSH_Excel_sql(id_list,is_single = Is_single)
    
        output = Sim_Output(
            event = event,
            num = num,
            gd_ids= gd_ids,
            keywords = keywords
        )

        logger.info(f"<<< code=200, msg=success, event={event}, num={num},gd_ids={gd_ids},keywords={keywords}\n")
        return SimeventResponse(code=200, msg="success", results=output)
        
    except Exception as e:
        logger.error(f"<<< code=500, msg=fail: {e}\n")
        return SimeventResponse_error(code=500, msg=f"fail: {e}")

def api_start(host, port):
    
    app = FastAPI()

    app.post("/sim_event", response_model=SimeventResponse)(Sim_event)
    app.post("/sim_event_excel", response_model=SimeventResponse)(Sim_event_excel)
    app.post("/sim_event_sql", response_model=SimeventResponse)(Sim_event_sql)

    uvicorn.run(app, host=host, port=port)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Start chat with chatglm3")
    parser.add_argument("--host", type=str, default="0.0.0.0")
    parser.add_argument("--port", type=int, default=8000)

    # 初始化消息
    args = None
    args = parser.parse_args()
    api_start(args.host, args.port)
    
